#include <iostream>
#include <strings.h>  //for bzero
#include <stdlib.h>
#include "SockServer.h"

using namespace std;


SockServer::SockServer()
{
	servaddrlen=sizeof(servaddr);
	bzero((struct sockaddr*)&servaddr,servaddrlen);
	
	cliaddrlen=sizeof(cliaddr);
	bzero((struct sockaddr*)&cliaddr,cliaddrlen);

	inBuf=(char *)malloc(1024);
	outBuf=(char *)malloc(1024);
}

SockServer::~SockServer()
{
	free(inBuf);
	free(outBuf);
	close(sockfd);
}

/*
 * set information of sockaddr structure,
 * Input:
 *		ip address in string type
 *		port whitch listen to
 *		family, AF_INET for default
 */
bool SockServer::SetAddr(short port)
{
	
	servaddr.sin_family=AF_INET;
	servaddr.sin_port=htons(port);
	servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
    
    return true;   
}

/*
 *
 *
 *
 */
bool SockServer::Socket()
{

	sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(sockfd < 0){
		Err();
		return false;
	}
	
	return true;
	
}

/*
 *
 *
 */
bool SockServer::Bind()
{
	int ret;
	
	ret=bind(sockfd,(struct sockaddr*)&servaddr,servaddrlen);
	if(0 != ret){
		Err();
		return false;	
	}
	
	return true;
}

bool SockServer::Listen(int backlog)
{
	int ret;
	
	ret=listen(sockfd,backlog);
	if(0 != ret){
		Err();
		return false;	
	}
	
	return true;
}

int SockServer::Accept()
{
	int fd;
	
	fd = accept(sockfd,(struct sockaddr*)&cliaddr,&cliaddrlen);
	if(fd == -1){
		Err();
		return -1;	
	}
	
	return fd;
}

bool SockServer::Send()
{
	size_t ret;
	
	ret = sendto(clifd,outBuf,1024,0,(struct sockaddr*)&cliaddr,
					cliaddrlen);
	if(ret < 0){
		Err();
		return false;	
	}
	
	return true;
}

bool SockServer::Receive()
{
	size_t ret;
	
	bzero(inBuf,1024);
	ret = recvfrom(clifd,inBuf,1024,0,(struct sockaddr*)&cliaddr,
					&cliaddrlen);
	if(ret < 0){
		Err();
		return false;	
	}
	return true;
}

/*
 * The interface of the server,which is used by common users.
 * Input:
 *		listening port number
 * Return value:
 *		ErrNone if successful,
 *		other error code if failed.		
 */
bool SockServer::StartServer(int port)
{
	int ret;

	cout<<"Starting server..."<<endl;
	
	if(!Socket()){
		return false;
	}
	
	SetAddr(port);
	
	if(!Bind()){
		return false;
	}
	
	if(!Listen()){
		return false;	
	}	
	
	cout<<"Server running..."<<endl;
	cout<<"Waiting to reseive message..."<<endl;

	while(true){
		int fd;	

		clifd = Accept();
		if(clifd == -1){
			cout<<errMessage<<endl;
			continue;
		}		
		
		ret=Receive();
		if(ret < 0){
			Err();
			close(fd);
			return false;	
		}
		cout<<"Received message: "<<inBuf<<endl;
		
		outBuf = "Have received your message,Thanks!";
		cout<<"Sending message..."<<endl;
		ret=Send();
		if(ret < 0){
			Err();
			close(fd);
			return false;	
		}	
		
		close(fd);
	}
}	
